import React, { useState, useMemo } from 'react';
import {
  Card,
  Tree,
  Tabs,
  Tag,
  Space,
  Typography,
  Row,
  Col,
  Collapse,
  Timeline,
  Tooltip,
  Alert,
  Divider,
  Switch,
  Select,
  Empty
} from 'antd';
import {
  PlusOutlined,
  MinusOutlined,
  SwapOutlined,
  EditOutlined,
  BranchesOutlined,
  InfoCircleOutlined,
  EyeOutlined,
  EyeInvisibleOutlined,
  FilterOutlined
} from '@ant-design/icons';
import type { DataNode } from 'antd/es/tree';

const { Text, Title } = Typography;
const { TabPane } = Tabs;
const { Panel } = Collapse;
const { Option } = Select;

export interface FieldMapping {
  id: number;
  fieldPath: string;
  mappingType: 'field_added' | 'field_removed' | 'field_modified' | 'field_renamed' | 'type_changed' | 'value_transformed' | 'structure_changed';
  fromFieldName?: string;
  toFieldName?: string;
  fromValue?: any;
  toValue?: any;
  fromDataType?: string;
  toDataType?: string;
  fromValuePreview?: string;
  toValuePreview?: string;
  transformationRule?: string;
  transformerName?: string;
  isSensitive: boolean;
  isRedacted: boolean;
  confidenceScore?: number;
  validationStatus: string;
  description?: string;
  severity?: 'low' | 'medium' | 'high';
  isCritical?: boolean;
}

export interface FieldDiffViewerProps {
  mappings: FieldMapping[];
  fromPhaseData?: Record<string, any>;
  toPhaseData?: Record<string, any>;
  fromPhaseName?: string;
  toPhaseName?: string;
  className?: string;
}

const FieldDiffViewer: React.FC<FieldDiffViewerProps> = ({
  mappings = [],
  fromPhaseData,
  toPhaseData,
  fromPhaseName = '源数据',
  toPhaseName = '目标数据',
  className
}) => {
  const [activeTab, setActiveTab] = useState('diff');
  const [showSensitive, setShowSensitive] = useState(false);
  const [filterType, setFilterType] = useState<string | undefined>();
  const [filterSeverity, setFilterSeverity] = useState<string | undefined>();

  // 过滤映射
  const filteredMappings = useMemo(() => {
    return mappings.filter(mapping => {
      if (!showSensitive && mapping.isSensitive) return false;
      if (filterType && mapping.mappingType !== filterType) return false;
      if (filterSeverity && mapping.severity !== filterSeverity) return false;
      return true;
    });
  }, [mappings, showSensitive, filterType, filterSeverity]);

  // 获取映射类型的图标
  const getMappingIcon = (type: string) => {
    const icons = {
      field_added: <PlusOutlined style={{ color: '#52c41a' }} />,
      field_removed: <MinusOutlined style={{ color: '#ff4d4f' }} />,
      field_modified: <EditOutlined style={{ color: '#1890ff' }} />,
      field_renamed: <SwapOutlined style={{ color: '#722ed1' }} />,
      type_changed: <BranchesOutlined style={{ color: '#fa8c16' }} />,
      value_transformed: <EditOutlined style={{ color: '#13c2c2' }} />,
      structure_changed: <BranchesOutlined style={{ color: '#eb2f96' }} />
    };
    return icons[type as keyof typeof icons] || <InfoCircleOutlined />;
  };

  // 获取映射类型的颜色
  const getMappingColor = (type: string) => {
    const colors = {
      field_added: 'success',
      field_removed: 'error',
      field_modified: 'processing',
      field_renamed: 'purple',
      type_changed: 'warning',
      value_transformed: 'cyan',
      structure_changed: 'magenta'
    };
    return colors[type as keyof typeof colors] || 'default';
  };

  // 获取严重性颜色
  const getSeverityColor = (severity: string) => {
    const colors = {
      low: 'green',
      medium: 'orange',
      high: 'red'
    };
    return colors[severity as keyof typeof colors] || 'default';
  };

  // 构建差异树结构
  const buildDiffTree = (data: Record<string, any>, prefix = ''): DataNode[] => {
    if (!data) return [];

    return Object.entries(data).map(([key, value]) => {
      const currentPath = prefix ? `${prefix}.${key}` : key;
      const relatedMapping = filteredMappings.find(m => 
        m.fieldPath === currentPath || m.fieldPath.startsWith(currentPath + '.')
      );

      const node: DataNode = {
        title: (
          <Space>
            <Text>{key}</Text>
            {relatedMapping && (
              <>
                {getMappingIcon(relatedMapping.mappingType)}
                <Tag color={getMappingColor(relatedMapping.mappingType)} size="small">
                  {relatedMapping.mappingType.replace(/_/g, ' ')}
                </Tag>
              </>
            )}
          </Space>
        ),
        key: currentPath,
        children: []
      };

      if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
        node.children = buildDiffTree(value, currentPath);
      } else {
        node.isLeaf = true;
      }

      return node;
    });
  };

  // 渲染值比较
  const renderValueComparison = (mapping: FieldMapping) => {
    const isValueChanged = mapping.fromValue !== mapping.toValue;
    
    return (
      <Row gutter={16}>
        <Col span={12}>
          <Card size="small" title={`${fromPhaseName} (${mapping.fromDataType || 'unknown'})`}>
            <Text 
              code={typeof mapping.fromValue === 'object'}
              type={isValueChanged ? 'danger' : 'default'}
            >
              {mapping.isRedacted ? '[已脱敏]' : (mapping.fromValuePreview || String(mapping.fromValue || 'undefined'))}
            </Text>
          </Card>
        </Col>
        <Col span={12}>
          <Card size="small" title={`${toPhaseName} (${mapping.toDataType || 'unknown'})`}>
            <Text 
              code={typeof mapping.toValue === 'object'}
              type={isValueChanged ? 'success' : 'default'}
            >
              {mapping.isRedacted ? '[已脱敏]' : (mapping.toValuePreview || String(mapping.toValue || 'undefined'))}
            </Text>
          </Card>
        </Col>
      </Row>
    );
  };

  // 渲染映射详情
  const renderMappingDetails = () => {
    return (
      <Collapse accordion>
        {filteredMappings.map((mapping, index) => (
          <Panel
            key={mapping.id}
            header={
              <Space>
                {getMappingIcon(mapping.mappingType)}
                <Text strong>{mapping.fieldPath}</Text>
                <Tag color={getMappingColor(mapping.mappingType)} size="small">
                  {mapping.mappingType.replace(/_/g, ' ')}
                </Tag>
                {mapping.severity && (
                  <Tag color={getSeverityColor(mapping.severity)} size="small">
                    {mapping.severity}
                  </Tag>
                )}
                {mapping.isCritical && <Tag color="volcano" size="small">关键</Tag>}
                {mapping.isSensitive && <Tag color="red" size="small">敏感</Tag>}
              </Space>
            }
          >
            <div>
              {mapping.description && (
                <Alert 
                  message={mapping.description} 
                  type="info" 
                  showIcon 
                  style={{ marginBottom: 16 }}
                />
              )}

              {mapping.transformationRule && (
                <div style={{ marginBottom: 16 }}>
                  <Text strong>转换规则: </Text>
                  <Text>{mapping.transformationRule}</Text>
                </div>
              )}

              {mapping.transformerName && (
                <div style={{ marginBottom: 16 }}>
                  <Text strong>转换器: </Text>
                  <Tag>{mapping.transformerName}</Tag>
                </div>
              )}

              {(mapping.fromValue !== undefined || mapping.toValue !== undefined) && (
                <>
                  <Divider orientation="left">值对比</Divider>
                  {renderValueComparison(mapping)}
                </>
              )}

              <Divider orientation="left">元数据</Divider>
              <Row gutter={16}>
                <Col span={8}>
                  <Text strong>置信度: </Text>
                  <Text>{mapping.confidenceScore ? `${Math.round(mapping.confidenceScore * 100)}%` : '-'}</Text>
                </Col>
                <Col span={8}>
                  <Text strong>验证状态: </Text>
                  <Tag color={mapping.validationStatus === 'valid' ? 'green' : 'orange'}>
                    {mapping.validationStatus}
                  </Tag>
                </Col>
                <Col span={8}>
                  <Text strong>数据脱敏: </Text>
                  <Text>{mapping.isRedacted ? '是' : '否'}</Text>
                </Col>
              </Row>
            </div>
          </Panel>
        ))}
      </Collapse>
    );
  };

  // 渲染统计摘要
  const renderSummary = () => {
    const summary = filteredMappings.reduce((acc, mapping) => {
      acc[mapping.mappingType] = (acc[mapping.mappingType] || 0) + 1;
      return acc;
    }, {} as Record<string, number>);

    const criticalCount = filteredMappings.filter(m => m.isCritical).length;
    const sensitiveCount = filteredMappings.filter(m => m.isSensitive).length;

    return (
      <Row gutter={16}>
        <Col span={16}>
          <Card size="small" title="变化类型统计">
            <Space wrap>
              {Object.entries(summary).map(([type, count]) => (
                <Space key={type}>
                  {getMappingIcon(type)}
                  <Tag color={getMappingColor(type)}>
                    {type.replace(/_/g, ' ')}: {count}
                  </Tag>
                </Space>
              ))}
            </Space>
          </Card>
        </Col>
        <Col span={8}>
          <Card size="small" title="特殊标记">
            <Space direction="vertical">
              <div>
                <Text strong>关键字段变化: </Text>
                <Tag color={criticalCount > 0 ? 'volcano' : 'green'}>
                  {criticalCount}
                </Tag>
              </div>
              <div>
                <Text strong>敏感数据: </Text>
                <Tag color={sensitiveCount > 0 ? 'red' : 'green'}>
                  {sensitiveCount}
                </Tag>
              </div>
              <div>
                <Text strong>总变化数: </Text>
                <Tag color="blue">{filteredMappings.length}</Tag>
              </div>
            </Space>
          </Card>
        </Col>
      </Row>
    );
  };

  // 渲染时间线视图
  const renderTimeline = () => {
    const timelineItems = filteredMappings.map((mapping, index) => ({
      children: (
        <div>
          <Space>
            {getMappingIcon(mapping.mappingType)}
            <Text strong>{mapping.fieldPath}</Text>
            <Tag color={getMappingColor(mapping.mappingType)} size="small">
              {mapping.mappingType.replace(/_/g, ' ')}
            </Tag>
          </Space>
          <div style={{ marginTop: 8 }}>
            <Text type="secondary">{mapping.description || mapping.transformationRule}</Text>
          </div>
        </div>
      )
    }));

    return (
      <Timeline
        mode="left"
        items={timelineItems}
      />
    );
  };

  if (mappings.length === 0) {
    return (
      <Empty 
        description="无字段映射数据" 
        image={Empty.PRESENTED_IMAGE_SIMPLE}
      />
    );
  }

  return (
    <div className={className}>
      {/* 过滤控制栏 */}
      <Card size="small" style={{ marginBottom: 16 }}>
        <Row gutter={16} align="middle">
          <Col span={6}>
            <Space>
              <EyeInvisibleOutlined />
              <Text>显示敏感数据:</Text>
              <Switch 
                checked={showSensitive} 
                onChange={setShowSensitive}
                size="small"
              />
            </Space>
          </Col>
          <Col span={6}>
            <Space>
              <FilterOutlined />
              <Select
                placeholder="筛选类型"
                allowClear
                value={filterType}
                onChange={setFilterType}
                style={{ width: 150 }}
                size="small"
              >
                <Option value="field_added">新增</Option>
                <Option value="field_removed">移除</Option>
                <Option value="field_modified">修改</Option>
                <Option value="field_renamed">重命名</Option>
                <Option value="type_changed">类型变化</Option>
                <Option value="value_transformed">值转换</Option>
                <Option value="structure_changed">结构变化</Option>
              </Select>
            </Space>
          </Col>
          <Col span={6}>
            <Select
              placeholder="筛选严重性"
              allowClear
              value={filterSeverity}
              onChange={setFilterSeverity}
              style={{ width: 120 }}
              size="small"
            >
              <Option value="low">低</Option>
              <Option value="medium">中</Option>
              <Option value="high">高</Option>
            </Select>
          </Col>
          <Col span={6}>
            <Text type="secondary">
              显示 {filteredMappings.length} / {mappings.length} 项变化
            </Text>
          </Col>
        </Row>
      </Card>

      {/* 统计摘要 */}
      {renderSummary()}

      <Divider />

      {/* 主要内容区域 */}
      <Tabs activeKey={activeTab} onChange={setActiveTab}>
        <TabPane tab="差异对比" key="diff">
          {renderMappingDetails()}
        </TabPane>

        <TabPane tab="时间线视图" key="timeline">
          {renderTimeline()}
        </TabPane>

        {fromPhaseData && toPhaseData && (
          <TabPane tab="树结构对比" key="tree">
            <Row gutter={16}>
              <Col span={12}>
                <Card size="small" title={fromPhaseName}>
                  <Tree
                    treeData={buildDiffTree(fromPhaseData)}
                    defaultExpandAll
                    showIcon
                  />
                </Card>
              </Col>
              <Col span={12}>
                <Card size="small" title={toPhaseName}>
                  <Tree
                    treeData={buildDiffTree(toPhaseData)}
                    defaultExpandAll
                    showIcon
                  />
                </Card>
              </Col>
            </Row>
          </TabPane>
        )}
      </Tabs>
    </div>
  );
};

export default FieldDiffViewer;